package test3;

/**
 * @Author Jun jie Yi
 * 2022/4/21 20:29
 */
public class Demo3 {
    public static void main(String[] args) {
        System.out.println(longestPalindrome("babad"));
    }

    public static String longestPalindrome(String s) {
        int len = s.length();
        int max_i = 0, max_j = 0;
        int[][] dp = new int[len][len];
        //将对角线赋值为 1
        for (int i = 0; i < dp.length; i++) {
            dp[i][i] = 1;
        }
        for (int i = len - 2; i >= 0; i--) {
            for (int j = i + 1; j < len; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;
                } else {
                    dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]);
                }
                //找出最长对应的 i 和 j
                if (j - i + 1 == dp[i][j] && max_j - max_i < j - i) {
                    max_i = i;
                    max_j = j;
                }
            }
        }
        return s.substring(max_i, max_j + 1);
    }
}
